package com.yunqiao.service.api.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunqiao.common.consts.AppConsts;
import com.yunqiao.common.exception.CustomApiException;
import com.yunqiao.common.utils.MapToolsUtils;
import com.yunqiao.common.utils.PageUtils;
import com.yunqiao.common.utils.Query;
import com.yunqiao.service.api.ApplyPartnerService;
import com.yunqiao.service.api.DistrictPriceService;
import com.yunqiao.service.api.entity.ApplyPartnerEntity;
import com.yunqiao.service.api.entity.DistrictPriceEntity;
import com.yunqiao.service.api.entity.UserEntity;
import com.yunqiao.service.api.mapper.ApplyPartnerMapper;
import com.yunqiao.service.api.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service("applyPartnerService")
public class ApplyPartnerServiceImpl extends ServiceImpl<ApplyPartnerMapper, ApplyPartnerEntity> implements ApplyPartnerService {

    @Autowired
    private ApplyPartnerMapper applyPartnerMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DistrictPriceService districtPriceService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //各种查询条件的过滤,在此进行
        QueryWrapper<ApplyPartnerEntity> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(MapUtil.getStr(params, "key"))) {
            queryWrapper.and(qw -> qw.or().like("name", MapUtil.getStr(params, "key")).or().like("phone", MapUtil.getStr(params, "key")));
        }
        if (StrUtil.isNotEmpty(MapUtil.getStr(params, "state"))) {
        	queryWrapper.apply("state in ("+MapUtil.getStr(params, "state")+")");
        }
        IPage<ApplyPartnerEntity> page = this.page(new Query<ApplyPartnerEntity>(params).getPage(),queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public ApplyPartnerEntity getReason(Long userId) {
        ApplyPartnerEntity applyPartnerEntity = applyPartnerMapper.selectOne(new QueryWrapper<ApplyPartnerEntity>().eq("user_id", userId));
        return applyPartnerEntity;
    }

    @Override
    public void saveApplyPartner(ApplyPartnerEntity applyPartner) {
        ApplyPartnerEntity applyPartnerEntity = this.applyPartnerMapper.selectOne(new QueryWrapper<ApplyPartnerEntity>()
            .eq("user_id", applyPartner.getUserId()));
        if (applyPartnerEntity == null) {
            DistrictPriceEntity districtPrice =  districtPriceService.getById(1);
            applyPartner.setMoneyFeeNumber(applyPartner.getMoneyFee());
            applyPartner.setMoneyFee(districtPrice.getPartnerPrice());
            applyPartner.setSysFee(districtPrice.getSysPrice());
            this.applyPartnerMapper.insert(applyPartner);
        } else {
            if (applyPartnerEntity.getState().equals(AppConsts.USER_APPLY_PARTNER_STATE_1)) {
                throw new CustomApiException("你已经是合伙人了");
            }
            if (applyPartnerEntity.getState().equals(AppConsts.USER_APPLY_PARTNER_STATE_0)) {
                throw new CustomApiException("你已经申请了");
            }
            applyPartner.setId(applyPartnerEntity.getId());
            applyPartner.setState(AppConsts.USER_APPLY_PARTNER_STATE_0);
            applyPartnerMapper.updateById(applyPartner);
        }

    }

    @Override
    public void agree(Long id) {
        //修改状态为已同意
        ApplyPartnerEntity applyPartnerEntity = applyPartnerMapper.selectById(id);
        applyPartnerEntity.setState(AppConsts.USER_APPLY_PARTNER_STATE_1);
        applyPartnerMapper.updateById(applyPartnerEntity);
        UserEntity userEntity = userMapper.selectById(applyPartnerEntity.getUserId());
        userEntity.setState(AppConsts.USER_APPLY_PARTNER_STATE_1);
        userMapper.updateById(userEntity);
    }

    @Override
    public void refuse(ApplyPartnerEntity applyPartner) {
        //修改状态为已拒绝
        ApplyPartnerEntity applyPartnerEntity = applyPartnerMapper.selectById(applyPartner.getId());
        applyPartnerEntity.setState(AppConsts.USER_APPLY_PARTNER_STATE_2);
        applyPartnerEntity.setReason(applyPartner.getReason());
        applyPartnerMapper.updateById(applyPartnerEntity);
        UserEntity userEntity = userMapper.selectById(applyPartnerEntity.getUserId());
        userEntity.setState(AppConsts.USER_APPLY_PARTNER_STATE_2);
        userMapper.updateById(userEntity);
    }

    @Override
    public List<Dict> getPosition() {
        List<Dict> dictList = new ArrayList<>();
        List<ApplyPartnerEntity> list = this.applyPartnerMapper.selectList(new QueryWrapper<>());
        if (ObjectUtil.isNotNull(list)) {
            list.stream().forEach(applyPartner -> {
                //根据省市区转换经纬度
                String location = MapToolsUtils.getLocation(applyPartner.getProvince() + applyPartner.getCity() + applyPartner.getArea() + applyPartner.getDetail());
                String[] split = location.split(",");

                if (ArrayUtil.isNotEmpty(split) && split.length == 2) {
                    dictList.add(Dict.create().set("position", new Double[]{new Double(split[0]), new Double(split[1])}));
                }
            });
        }
        return dictList;
    }

    @Override
    public void saveAplyPartner(ApplyPartnerEntity applyPartner) {
        Integer count = applyPartnerMapper.selectCount(new QueryWrapper<ApplyPartnerEntity>()
                .eq("province", applyPartner.getProvince())
                .eq("city", applyPartner.getCity())
                .eq("area", applyPartner.getArea()));
        if (count > 0) {
            throw new RuntimeException("这个城市有城市合伙人了");
        }
        if (applyPartner.getMoneyFee().add(applyPartner.getSysFee()).doubleValue() >= 1) {
            throw new CustomApiException("参数异常");
        }
        this.applyPartnerMapper.insert(applyPartner);
    }

}
